package com.ctlele.team.space.util;

import com.ctlele.team.space.entity.vo.ChatMessageVo;

import java.util.List;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;

import okhttp3.WebSocket;

/**
 * 临时写的工具类
 * TODO: 后期应当持久化到SQLite 并合理处理消息推送的问题
 */
public class MessageUtils {

    private static final String TAG = "MessageUtils";

    /**
     * TODO: 后期应将此Map改成表
     */
    private static final Map<String, List<ChatMessageVo>> CHAT_MSG = new ConcurrentHashMap<>();

    private static WebSocket SENDER;

    public static synchronized void cache(String from, ChatMessageVo message) {
        List<ChatMessageVo> history = CHAT_MSG.get(from);
        if (history == null) {
            history = new CopyOnWriteArrayList<>();
        }
        history.add(message);
        CHAT_MSG.put(from, history);
    }

    public static synchronized void cache(String from, List<ChatMessageVo> message) {
        List<ChatMessageVo> history = CHAT_MSG.get(from);
        if (history == null) {
            history = new CopyOnWriteArrayList<>();
        }
        history.addAll(message);
        CHAT_MSG.put(from, history);
    }

    public static List<ChatMessageVo> interceptList(String from) {
        return CHAT_MSG.remove(from);
    }

    public static void sort(String from) {
        List<ChatMessageVo> history = CHAT_MSG.get(from);
        if (history == null || history.isEmpty()) {
            return;
        }
        history.sort((o1, o2) -> -Long.compare(o1.getGmtCreate().getTime(), o2.getGmtCreate().getTime()));
    }

    public static void push(String text) {
        if (SENDER == null) return;
        SENDER.send(text);
    }

    public static void setSender(WebSocket webSocket) {
        SENDER = webSocket;
    }
}
